//
//  SLAccessManagerView.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/26.
//

#import "SLAccessSettingView.h"
#import "SLAccessSettingCell.h"



static  NSString *const kCellId = @"SLAccessSettingCell";


@interface SLAccessSettingView ()<UITableViewDelegate,UITableViewDataSource>{
    UIButton *_curBtn;
    SLLockKeyModel *_keyModel;
    NSString *_dateFormart;
    NSString *_timeFormart;
}
@property (nonatomic, strong)NSArray *selectDays;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;

@end

@implementation SLAccessSettingView
-(void)awakeFromNib{
    [super awakeFromNib];
    _dateFormart = @"MMM. d, yyyy";
    _timeFormart = @"MMM. d, yyyy  HH:mm";
    _topView.layer.cornerRadius = 20;
    _topView.layer.masksToBounds = YES;
    
    _bottomBgView.layer.cornerRadius = 20;
    _bottomBgView.layer.masksToBounds = YES;
    
    _timeBgView.layer.cornerRadius = 20;
    _timeBgView.layer.masksToBounds = YES;

    [_bottomBgView addSubview:self.tableView];
    
    _listContentLbl1.layer.cornerRadius = 10;
    _listContentLbl1.layer.masksToBounds = YES;
    _listContentLbl2.layer.cornerRadius = 10;
    _listContentLbl2.layer.masksToBounds = YES;
    _listContentLbl3.layer.cornerRadius = 10;
    _listContentLbl3.layer.masksToBounds = YES;
   
    _startTimeLbl.layer.cornerRadius = 10;
    _startTimeLbl.layer.masksToBounds = YES;
    _endTimeLbl.layer.cornerRadius = 10;
    _endTimeLbl.layer.masksToBounds = YES;
    
    _listLbl1.text = kLocalString(@"Time repeat");
    
    [self addTapWith:_listContentLbl2 tag:1];
    [self addTapWith:_startTimeLbl tag:2];
    [self addTapWith:_listContentLbl3 tag:3];
    [self addTapWith:_endTimeLbl tag:4];
    [self addTapWith:_listView4 tag:5];
    [self addTapWith:_listView5 tag:6];
}

-(void)addTapWith:(UIView *)view tag:(NSInteger)tag{
    kWeakSelf(self);
    view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        if (weakself.listBlock) weakself.listBlock(tag);
    }];
    [view addGestureRecognizer:tap];
}

- (IBAction)btnAction:(id)sender {
    if (sender == _editBtn) {
        if (self.btnBlock) {
            self.btnBlock(1);
        }
    }
}

- (IBAction)changeBtnAction:(id)sender {
    if (self.switchBlock) {
        self.switchBlock(_changeBtn.isOn);
    }
}

- (IBAction)timeChangeBtnAction:(UISwitch *)sender {
    CGFloat timeBgHeight;
    if (_keyModel.lockType == 1) {
        timeBgHeight = 250;
    }else{
        timeBgHeight = 300;
    }
    _lineRepeat.hidden = NO;
    _line4.hidden = NO;
    _line3.hidden = NO;
    
    if (sender.isOn > 0) {
        _timeChangeBtn.on = YES;
        _listView4Height.constant = 50;
        _listView4.hidden = NO;
    }else{
        _listView4.hidden = YES;
        _timeChangeBtn.on = NO;
        _listView4Height.constant = 0;
        timeBgHeight -= 50;
    }
    if (timeBgHeight == 50) {
        _line0.hidden = YES;
    }
    if (timeBgHeight == 150) {
        _line3.hidden = YES;
    }
    if (timeBgHeight == 200) {
        _lineRepeat.hidden = YES;
    }
    if (timeBgHeight == 250) {
        _line4.hidden = YES;
    }
    _timeBgViewHeight.constant = timeBgHeight;
    if (self.listBlock) {
        self.listBlock(7);
    }
}

-(void)refreshWith:(SLLockKeyModel *)model{
    _topContentLbl4.text = model.createBy;
    _topContentLbl3.text = [NSString convertDateString:model.createTime];
    _changeBtn.on = [kSTRING(model.status) isEqualToString:@"0"];
    _keyModel = model;
    
    NSString *keyStr;
    if (_keyModel.keyType == 1) {
        keyStr = kLocalString(@"Permanent");
    }else if (_keyModel.keyType == 2){
        keyStr = kLocalString(@"Duration");
    }else if (_keyModel.keyType == 3){
        keyStr = kLocalString(@"One Time");
    }
    _topContentLbl1.text = _keyModel.keyName;
    _listContentLbl0.text = keyStr;
    
    //蓝牙钥匙才有分享
    CGFloat timeBgHeight;
    if (_keyModel.lockType == 1) {
        timeBgHeight = 250;
        _listView5.hidden = YES;
        _listView5Height.constant = 0;
        _topLbl2.text = kLocalString(@"Disable fingerprint access");
    }else{
        timeBgHeight = 300;
        _addBtn.hidden = YES;
        _disableBgHeight.constant = 0;
        _disableBgView.hidden = YES;
        _bottomTipLbl.hidden = YES;
        _topViewHeight.constant = 150;
        _topLbl2.text = kLocalString(@"Disable bluetooth access");
    }
    
    //有时间，一次性钥匙或者时间段钥匙
    if (model.startTime.length > 0) {
        if (_keyModel.keyType == 3) {//一次性钥匙
            NSString *startTime = [NSString convertDateString:model.startTime outFormart:_timeFormart];
            NSString *endTime = [NSString convertDateString:model.endTime outFormart:_timeFormart];
            _listContentLbl2.text = startTime;
            _listContentLbl3.text = endTime;
            CGSize size2 = STRING_SIZE_FONT(1000, startTime, kFont(16));
            CGSize size3 = STRING_SIZE_FONT(1000, endTime, kFont(16));
            _listContent2Width.constant = size2.width+30;
            _listContent3Width.constant = size3.width+30;
            _endTimeWidth.constant = 0;
            _endLeftSpace.constant = 0;
            _startTimeWidth.constant = 0;
            _startLeftSpace.constant = 0;
        }else{//时间段钥匙
            NSString *startTime = [NSString convertDateString:model.startTime outFormart:_dateFormart];
            NSString *endTime = [NSString convertDateString:model.endTime outFormart:_dateFormart];
            _listContentLbl2.text = startTime;
            _listContentLbl3.text = endTime;
            _startTimeLbl.text = model.dayStart;
            _endTimeLbl.text = model.dayEnd;
            _listContentLbl4.text = [self dayStr];
            if (model.weekDays.count > 0) {
                _timeChangeBtn.on = YES;
                _listView4Height.constant = 50;
                _listView4.hidden = NO;
            }else{
                _timeChangeBtn.on = NO;
                _listView4Height.constant = 0;
                _listView4.hidden = YES;
                timeBgHeight -= 50;
            }
            _listContent2Width.constant = 120;
            _listContent3Width.constant = 120;
            _endTimeWidth.constant = 60;
            _endLeftSpace.constant = 10;
            _startTimeWidth.constant = 60;
            _startLeftSpace.constant = 10;
        }
    }
    
    if (_keyModel.keyType == 1) {
        timeBgHeight -= 200;
        _listView1.hidden = _listView2.hidden = _listView3.hidden = _listView4.hidden = YES;
        _listView1Height.constant = _listView2Height.constant = _listView3Height.constant = _listView4Height.constant = 0;
    }else if(_keyModel.keyType == 3){
        timeBgHeight -= 100;
        _listView1.hidden = _listView4.hidden = YES;
        _listView1Height.constant = _listView4Height.constant = 0;
    }
    _timeBgViewHeight.constant = timeBgHeight;
    if (timeBgHeight == 50) {
        _line0.hidden = YES;
    }
    if (timeBgHeight == 150) {
        _line3.hidden = YES;
    }
    if (timeBgHeight == 200) {
        _lineRepeat.hidden = YES;
    }
    if (timeBgHeight == 250) {
        _line4.hidden = YES;
    }
    
    [self.dataArray removeAllObjects];
    [_dataArray addObjectsFromArray:_keyModel.fingers];
    CGFloat height = _dataArray.count * 50;
    _bottomViewHeight.constant = height;
    _tableView.frame = CGRectMake(0, 0, kScreenWidth-40, height);
    [_tableView reloadData];
}

-(NSString *)dayStr{
    
    NSMutableArray *arr = [NSMutableArray new];
    [_keyModel.weekDays enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:@"0"]) {
            [arr addObject:kLocalString(@"Sunday")];
        }else if ([obj isEqualToString:@"1"]){
            [arr addObject:kLocalString(@"Monday")];
        }else if ([obj isEqualToString:@"2"]){
            [arr addObject:kLocalString(@"Tuesday")];
        }else if ([obj isEqualToString:@"3"]){
            [arr addObject:kLocalString(@"Wednesday")];
        }else if ([obj isEqualToString:@"4"]){
            [arr addObject:kLocalString(@"Thursday")];
        }else if ([obj isEqualToString:@"5"]){
            [arr addObject:kLocalString(@"Friday")];
        }else if ([obj isEqualToString:@"6"]){
            [arr addObject:kLocalString(@"Saturday")];
        }
    }];
    _selectDays = arr;
    
    if (_selectDays.count == 7) {
        return kLocalString(@"Every day");
    }else{
        NSString *dayStr = [_selectDays componentsJoinedByString:@"./"];
        return dayStr;
    }
}

- (IBAction)addFingerAction:(id)sender {
    if (self.btnBlock) self.btnBlock(2);
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLAccessSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SLLockFingerModel *model = _dataArray[indexPath.row];
    
    cell.line.hidden = indexPath.row == _dataArray.count-1;
    cell.titleLbl.text = kReplace(model.fingName, @"-");
    return cell;
}

// 在 UITableViewDelegate 中实现以下方法
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建删除按钮
    kWeakSelf(self);
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:kLocalString(@"Delete") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 删除操作的实现
        [self deleteFingerDataWith:indexPath];
    }];
    
    // 创建编辑按钮
    UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:kLocalString(@"Edit") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 编辑操作的实现
        [weakself showInputView:indexPath];
    }];
    editAction.backgroundColor = [UIColor systemBlueColor];
    
    return @[deleteAction, editAction];
}

-(void)deleteFingerDataWith:(NSIndexPath *)indexPath{
    //先硬件端删除
    [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Deleting...")];
    SLLockFingerModel *model = self.dataArray[indexPath.row];
    
    //硬件端没有数据 - 直接删除
    if (kSTRING(model.accessId).length == 0) {
        [self deleteServerDataWith:indexPath];
        return;
    }
    
    [ZCTool connectDeviceWith:kCurClickDevice toast:@"" finish:^(BOOL isSuccess) {
        if (!isSuccess) {
            [ZCTool hideLoadingOnKeyWindow];
            return;
        }
        //连接上开始删除
        [[SLBluetoothManager sharedManager] deleteUserFingerAccessWith:model.uid accessId:model.accessId finish:^(NSString *commond, BOOL isDeleteSuccess, id data, NSString *errorMsg) {
            //删除失败
            if (!isDeleteSuccess) {
                [ZCTool hideLoadingOnKeyWindow];
                kShowToast(@"Delete faild");
                return;
            }
            //硬件端删除成功，再删除服务端的指纹数据
            [self deleteServerDataWith:indexPath];
        }];
    }];
}

-(void)deleteServerDataWith:(NSIndexPath *)indexPath{
    SLLockFingerModel *model = self.dataArray[indexPath.row];
    NSString *url = [NSString stringWithFormat:@"/msl_lock_key/LockFing/delete/%@",model.fingId];
    [ZKHttpManager deleteWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        
        //服务端删除成功
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
        self.bottomViewHeight.constant = self.dataArray.count * 50;
    }];
}


-(void)showInputView:(NSIndexPath *)indexPath{
    SLLockFingerModel *model = self.dataArray[indexPath.row];
    __weak SLInputAlertView *alert = [SLInputAlertView viewFromXIB];
    alert.titleLbl.text = kLocalString(@"Edit Name");
    [alert.tf setPlaceholderWithPlaceholderText:kLocalString(@"Enter finger name") withColor:KColor_placeholdar withFont:kFont(16)];
    [alert setBtnBlock:^(NSString *text, NSInteger btnIndex) {
        
        if (btnIndex == 1) {
            if (text.length == 0) {
                kShowToast(@"Enter finger name");
                return;
            }
            [alert removeFromSuperview];
            model.fingName = text;
            
            NSDictionary *params = @{@"fingId":model.fingId,
                                     @"fingName":model.fingName,
                                     @"accessId":model.accessId,
                                     @"uid":model.uid,
                                     @"keyId":self->_keyModel.keyId};
            [ZCTool showLoadingOnKeyWindow];
            [ZKHttpManager postWithPath:@"/msl_lock_key/LockFing/update" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                [ZCTool hideLoadingOnKeyWindow];
                if (!isSuccessed) {
                    kShowToast(message);
                    return;
                }
                [self->_tableView reloadData];
            }];
        }else{
            [alert removeFromSuperview];
        }
    }];
    [kAppWindow addSubview:alert];
}

// 如果要在左滑时才显示编辑按钮,需要实现以下方法
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SLLockKeyModel *model = _dataArray[indexPath.row];
    if (self.cellCilckBlock) {
        self.cellCilckBlock(model);
    }
}


#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}


@end
